package es.manuel.maa.util;

import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.jsf.FacesContextUtils;

public final class JSFUtil {

	private JSFUtil() {

	}

	public static void addGlobalMessage(String bundleName, String messageKey,
			FacesMessage.Severity severity) {
		FacesContext context = FacesContext.getCurrentInstance();
		context.addMessage(null, getMessage(bundleName, messageKey, severity));
	}

	public static FacesMessage getMessage(String bundleName, String messageKey,
			FacesMessage.Severity severity) {
		FacesMessage message = new FacesMessage();
		message.setSeverity(severity);
		message.setSummary(getI18N(bundleName, messageKey));
		return message;
	}

	public static String getI18N(String bundleName, String messageKey) {
		FacesContext context = FacesContext.getCurrentInstance();
		ResourceBundle bundle = context.getApplication().getResourceBundle(
				context, bundleName);
		return bundle.getString(messageKey);
	}

	public static <E> E getBean(String beanName, Class<E> beanClass) {
		FacesContext context = FacesContext.getCurrentInstance();
		WebApplicationContext webApplicationContext = FacesContextUtils
				.getRequiredWebApplicationContext(context);
		return webApplicationContext.getBean(beanName, beanClass);
	}

}
